package com.longsichao.lscframe.tools;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author SONG GUANYULONGSICHAO (leo.song[at]outlook[dot]com)
 * @version 1
 */
public class FileManager {
    private static final String LOGFILE_NAME_FORMAT = "%1$tF.log";

    public static String getLogFileNamePath(Context context) {
        if (context == null) {
            throw new NullPointerException("Not set application context.");
        }
        StringBuilder name = new StringBuilder();
        File dir = context.getExternalFilesDir(null);
        if (dir != null) {
            name.append(dir.getAbsolutePath());
        } else {
            name.append(context.getFilesDir().getAbsolutePath());
        }
        name.append(File.separator);
        name.append(String.format(Locale.CHINA, LOGFILE_NAME_FORMAT, System.currentTimeMillis()));
        return name.toString();
    }

    public static File getImageCachePath(Context context) {
        File dir = context.getExternalCacheDir();
        if (dir == null) {
            LSCLog.d("external cache dir unable.");
            dir = context.getCacheDir();
        }
        File path = new File(dir.getAbsolutePath() + File.separator + "image");
        if (!path.exists()) {
            boolean b = path.mkdirs();
            LSCLog.d("create image dir " + (b ? "success" : "fail"));
        }
        return path;
    }

    public static boolean isSdCardExist() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public static String getImageNameWithPath(Context context, Uri imageUri) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = context.getContentResolver().query(imageUri, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            return picturePath;
        } else {
            return "";
        }
    }

    public static String getImageNameWithoutPath(Context context, Uri imageUri) {
        String[] strings = getImageNameWithPath(context, imageUri).split("/");
        return strings[strings.length - 1];
    }

    public static String getImageNameWithoutPath(String imagePath) {
        String[] strings = imagePath.split("/");
        return strings[strings.length - 1];
    }

    public static Uri getOutputMediaFileUri(Context context) {
        return Uri.fromFile(getOutputMediaFile(context));
    }

    public static Uri getOutputMediaFileUri(File file) {
        return Uri.fromFile(file);
    }

    public static File getOutputMediaFile(Context context) {
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = getImageCachePath(context);
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) {
            LSCLog.d("failed to create directory");
            return null;
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");

        return mediaFile;
    }

    public static String encodeKey(String key) {
        if (key == null || key.length() == 0) {
            return null;
        }
        char[] s = key.toCharArray();
        String r = "";
        for (char c : s) {
            r += Integer.toHexString((int) c);
        }
        return r;
    }

    private FileManager() {
    }

}
